﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonControls;
using DevelopTool.Forms.DbForms.ColumnForms;
using DevelopTool.Forms.DbForms.ExecuteForms;
using DevelopTool.Forms.DbForms.FunctionForms;
using DevelopTool.Forms.DbForms.JobForms;
using DevelopTool.Forms.DbForms.PackageForms;
using DevelopTool.Forms.DbForms.ProcedureForms;
using DevelopTool.Forms.DbForms.ReferenceForms;
using DevelopTool.Forms.DbForms.SequenceForms;
using DevelopTool.Forms.DbForms.SynonymForms;
using DevelopTool.Forms.DbForms.TriggerForms;
using DevelopTool.Forms.DbForms.ViewForms;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.DbModels;
using Sunny.UI;

namespace DevelopTool.Forms.DbForms.TableForms
{
    /// <summary>
    /// 表信息
    /// </summary>
    public partial class OracleTableForm : BaseUIPage
    {
        /// <summary>
        /// 连接信息
        /// </summary>
        private DbInfo dbInfo;

        /// <summary>
        /// Oracle操作类
        /// </summary>
        private OracleDbBll oracleDbBll;

        /// <summary>
        /// 查询条件
        /// </summary>
        private string queryKeyword;

        /// <summary>
        /// 查询实例
        /// </summary>
        private string queryDataBase;

        /// <summary>
        /// 查询资源名
        /// </summary>
        private string queryInfoName;

        /// <summary>
        /// DataGridView列信息集合
        /// </summary>
        private List<DataGridColumn> dataGridColumns = new List<DataGridColumn>()//Width=250,Width=150
              {
                { new DataGridColumn("TABLE_NAME"){ColumnText="表名",Width=0,ColumnType = ColumnType.DefaultFilter|ColumnType.RowMain}},
                { new DataGridColumn("NUM_ROWS"){ColumnText="数据总计",Width=-1}},
                { new DataGridColumn("COMMENTS"){ColumnText="注释",Width=0,ColumnType = ColumnType.DefaultFilter}},
                { new DataGridColumn("OWNER"){ColumnText="实例",Width=100}},
                { new DataGridColumn("TEXT"){ColumnText="建表sql",Width=100,ColumnType = ColumnType.DefaultFilter|ColumnType.CanClick|ColumnType.LongText,ShowFormProperty=new ShowFormProperty(){
                BaseNameColumn="TABLE_NAME"
                } }},
                { new DataGridColumn("REFCOUNT"){ColumnText="依赖数量",Width=-1,ColumnType = ColumnType.CanClick}},
                { new DataGridColumn("TABLESPACE_NAME"){ColumnText="表空间",Width=120}},
                { new DataGridColumn("LAST_ANALYZED"){ColumnText="最近分析日期",Width=130,ColumnType = ColumnType.Hide}}
              };



        public OracleTableForm(DbInfo dbInfo)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
        }

        public OracleTableForm(DbInfo dbInfo,string queryKeyword)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
            this.queryKeyword = queryKeyword;
        }

        public OracleTableForm(DbInfo dbInfo,string queryDataBase,string queryInfoName)
        {
            InitializeComponent();

            this.dbInfo = dbInfo.CloneObj();
            this.queryDataBase = queryDataBase;
            this.queryInfoName = queryInfoName;
        }


        private void OracleTableInfoForm_Load(object sender,EventArgs e)
        {
            this.oracleDbBll = new OracleDbBll(dbInfo);

            InitDate();

            this.dataDisplayControl.DbInfo = this.dbInfo;

            this.dataDisplayControl.BindContextMenuStrip(this.ContextMenuStripDgv);//绑定右键菜单

        }


        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitDate()
        {
            DataTable dataTable = new DataTable();
            LoadingHelper.ShowLoading("获取表数据",() =>
                {
                    //查询指定数据库表信息
                    dataTable = oracleDbBll.GetTables(this.queryDataBase,this.queryInfoName);
                });

            this.dataDisplayControl.BindData(dataTable,this.dataGridColumns,"TABLE_NAME ASC");

            if(!string.IsNullOrEmpty(queryKeyword)) this.dataDisplayControl.Search(queryKeyword);
        }


        private void dataDisplayControl_DataGridViewCellClick(DataGridViewEventArgs dataGridViewEventArgs)
        {
            if(dataGridViewEventArgs.MouseButton == MouseButtons.Left)//判断点的是不是左键
            {
                if(dataGridViewEventArgs.Column.Name == "TEXT" && string.IsNullOrEmpty(dataGridViewEventArgs.Cell.Value.ToString()))
                {
                    string tableName = dataGridViewEventArgs.Row.Cells["TABLE_NAME"].Value.ToString();//取得表名
                    string owner = dataGridViewEventArgs.Row.Cells["OWNER"].Value.ToString();//取得表所有者
                    string ddlText = string.Empty;
                    LoadingHelper.ShowLoading($"获取表{tableName}建表sql语句",() =>
                    {
                        ddlText = oracleDbBll.GetTypeDDLText("TABLE",tableName,owner);
                    });

                    dataGridViewEventArgs.Cell.Value = ddlText;
                }

                if(dataGridViewEventArgs.Column.Name == "REFCOUNT" && string.IsNullOrEmpty(dataGridViewEventArgs.Cell.Value.ToString()))
                {
                    string objectName = dataGridViewEventArgs.Row.Cells["TABLE_NAME"].Value.ToString();//取得表名
                    string owner = dataGridViewEventArgs.Row.Cells["OWNER"].Value.ToString();//取得表所有者
                    string refCount = string.Empty;
                    LoadingHelper.ShowLoading($"获取{objectName}依赖关系数量",() =>
                    {
                        refCount = oracleDbBll.GetObjectRefCount("TABLE",objectName,owner);
                    });

                    dataGridViewEventArgs.Cell.Value = refCount;
                }
            }
        }


        #region 右键菜单事件

        /// <summary>
        /// 数据刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataDisplayControl_DataReLoad(object sender,EventArgs e)
        {
            InitDate();
        }

        private void 生成SelectSqlToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
            string sql = new DbManagerBll(dbInfo).GenerateSql("select",owner,tableName);
            Clipboard.SetText(sql);
            this.ShowSuccessNotifier("已复制select语句到剪贴板");
        }


        private void 生成InsertSqlToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
            string sql = new DbManagerBll(dbInfo).GenerateSql("insert",owner,tableName);
            Clipboard.SetText(sql);
            this.ShowSuccessNotifier("已复制insert语句到剪贴板");
        }

        private void 生成UpdateSqlToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
            string sql = new DbManagerBll(dbInfo).GenerateSql("update",owner,tableName);
            Clipboard.SetText(sql);
            this.ShowSuccessNotifier("已复制update语句到剪贴板");
        }

        private void 生成DeleteSqlToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
            string sql = new DbManagerBll(dbInfo).GenerateSql("delete",owner,tableName);
            Clipboard.SetText(sql);
            this.ShowSuccessNotifier("已复制delete语句到剪贴板");
        }


        private void 生成实体类ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string owner = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
            string entityCode = string.Empty;

            LoadingHelper.ShowLoading($"生成实体类代码",() =>
            {
                entityCode = new DbManagerBll(dbInfo).GenerateEntity(owner,tableName);
            });

            if(!string.IsNullOrEmpty(entityCode))
            {
                Clipboard.SetText(entityCode);
                this.ShowSuccessNotifier("已复制实体类代码到剪贴板");
            }
            else
            {
                this.ShowWarningNotifier("生成失败");
            }
        }


        private void 查询选定表数据ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                string dataBase = this.dataDisplayControl.SelectedRowDic["OWNER"];//设置数据库实例名

                string sql = $"select * from {dataBase}.{tableName} where 1=1";
                TabControlHelper.AddPageToTabControl(parentTabControl,new ExecuteSqlForm(dbInfo,sql),$"{dbInfo.NodeName}-查询",true,$"{tableName}-ExecuteSqlForm");
            }
        }


        private void 查看选定表字段ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                string dataBase = this.dataDisplayControl.SelectedRowDic["OWNER"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleTableColumnForm(dbInfo,dataBase,tableName),$"{dbInfo.NodeName}-字段",true,$"{tableName}-OracleTableColumnForm");
            }
        }


        private void 在视图中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleViewForm(dbInfo,tableName),$"{dbInfo.NodeName}-视图",true,$"{tableName}-OracleViewForm");
            }
        }


        private void 在函数中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleFunctionForm(dbInfo,tableName),$"{dbInfo.NodeName}-函数",true,$"{tableName}-OracleFunctionForm");
            }
        }

        private void 在存储过程中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleProcedureForm(dbInfo,tableName),$"{dbInfo.NodeName}-存储过程",true,$"{tableName}-OracleProcedureForm");
            }
        }


        private void 在触发器中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleTriggerForm(dbInfo,tableName),$"{dbInfo.NodeName}-触发器",true,$"{tableName}-OracleTriggerForm");
            }
        }

        private void 在Jobs中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleJobForm(dbInfo,tableName),$"{dbInfo.NodeName}-Jobs",true,$"{tableName}-OracleJobForm");
            }
        }

        private void 在同义词中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleSynonymForm(dbInfo,tableName),$"{dbInfo.NodeName}-同义词",true,$"{tableName}-OracleSynonymForm");
            }
        }

        private void 在包中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OraclePackageForm(dbInfo,tableName),$"{dbInfo.NodeName}-包",true,$"{tableName}-OraclePackageForm");
            }
        }

        private void 在序列中查找ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                string tableName = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleSequenceForm(dbInfo,tableName),$"{dbInfo.NodeName}-序列",true,$"{tableName}-OracleSequenceForm");
            }
        }

        private void 查看依赖关系ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string dataBase = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string name = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];

            UITabControl parentTabControl = this.GetParentControl<UITabControl>();
            if(parentTabControl != null)
            {
                TabControlHelper.AddPageToTabControl(parentTabControl,new OracleReferenceForm(this.dbInfo,dataBase,name,"TABLE"),$"{dbInfo.NodeName}-{name}依赖",true,$"{name}-OracleReferenceForm");
            }
        }

        private void 添加到分组ToolStripMenuItem_Click(object sender,EventArgs e)
        {
            string dataBase = this.dataDisplayControl.SelectedRowDic["OWNER"];
            string name = this.dataDisplayControl.SelectedRowDic["TABLE_NAME"];

            DbSourceGroupHelper.AddSourceToGroup(dataBase,name,"TResTable",this.dbInfo);
        }

        #endregion


    }
}
